#include "mainwindow.h"

#include <QDebug>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>

#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);
  initDBConnection();
  createTable();
}

MainWindow::~MainWindow() {
  delete ui;
  m_db.close();  // 关闭数据库连接
}

void MainWindow::initDBConnection() {
  m_db = QSqlDatabase::addDatabase("QMYSQL");  // 使用MySQL驱动
  m_db.setHostName("localhost");      // mysql 服務器 在本地安裝
  m_db.setDatabaseName("sample_02");  // 数据库名称
  m_db.setUserName("qt");
  m_db.setPassword("qt");

  if (!m_db.open()) {
    qDebug() << "Database error occurred: " << m_db.lastError().text();
    return;
  }

  qDebug() << "Connected to the database!";
}

void MainWindow::createTable() {
  if (m_db.isOpen()) {
    QSqlQuery query;
    query.exec(
        "CREATE TABLE IF NOT EXISTS people ("
        "id INT PRIMARY KEY AUTO_INCREMENT,"
        "name VARCHAR(100),"
        "age INT)");

    if (!query.isActive()) {
      qDebug() << "Failed to create table: " << query.lastError().text();
      return;
    }

    qDebug() << "Table created!";
  }
}
